package com.db.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * <p>
 *
 * </p>
 *
 * @author xsy
 * @date 2023年11月23日 14:38
 */
public class RandomUtils {

    public static int radom(int min, int max) {
        Random r=new Random();
        int result = r.nextInt(max-min+1)+min;
        return result;
    }

    public static String randomElemByArr(String... arg){
        return arg[radom(0,arg.length-1)];
    }
    /**
     * 生成随机时间
     * @param beginDate	开始时间范围
     * @param endDate	结束时间范围
     * @return
     */
    public static Date randomDate(Date beginDate,Date endDate){
        long before = beginDate.getTime();
        //默认获取当前时间
        Date d2 = new Date();
        if(endDate != null){
            d2 = endDate;
        }
        long after = d2.getTime();

        Random r = new Random();
        long randomDate = (long) (before + (r.nextFloat() * (after - before + 1)));
        return new Date(randomDate);
    }

    public static Date randomStrDate(String beginDate,String endDate) {
        //格式化时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //如果不需要时分秒，下面拼接00:00:00也不需要
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        //随机起始时间拼接时分秒
        beginDate += " 00:00:00";
        //解析时间
        Date d1 = null;
        try {
            d1 = sdf.parse(beginDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long before = d1.getTime();

        //默认获取当前时间
        Date d2 = new Date();
        if(endDate != null){
            //拼接时分秒
            endDate += " 00:00:00";
            try {
                d2 = sdf.parse(endDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        long after = d2.getTime();

        Random r = new Random();
        long randomDate = (long) (before + (r.nextFloat() * (after - before + 1)));
        return new Date(randomDate);
    }
}
